//
//  BTEToastTool.swift
//  BTE
//
//  Created by 张文 on 2025/8/30.
//


import UIKit
import MBProgressHUD

class BTEToastTool {
    
    // MARK: - 单例模式
    static let shared = BTEToastTool()
    
    private init() {}
    
    // 存储当前显示的HUD
    private var currentHUD: MBProgressHUD?
    
    // MARK: - 显示加载指示器
    /// 在指定视图上显示加载指示器
    /// - Parameters:
    ///   - message: 提示文字（可选）
    ///   - view: 目标视图（默认为主窗口）
    func showLoader(message: String? = nil, on view: UIView) {
        DispatchQueue.main.async {
            let targetView = view
            self.currentHUD?.hide(animated: false)
            
            let hud = MBProgressHUD.showAdded(to: targetView, animated: true)
            hud.mode = .indeterminate
            hud.label.text = message
            hud.removeFromSuperViewOnHide = true
            hud.bezelView.style = .solidColor // 使用纯色背景
            hud.bezelView.backgroundColor = .colorWithHex("#000000", alpha: 1)
            hud.contentColor = .white
            hud.removeFromSuperViewOnHide = true
            self.currentHUD = hud
        }
    }
    
    // MARK: - 显示成功提示
    func showSuccess(_ message: String, on view: UIView) {
        showResult(message, type: .success,on: view)
    }
    
    // MARK: - 显示错误提示
    func showError(_ message: String, on view: UIView) {
        showResult(message, type: .error,on: view)
    }
    
    // MARK: - 全局隐藏方法
    func hide() {
        DispatchQueue.main.async {
            self.currentHUD?.hide(animated: true)
            self.currentHUD = nil
        }
    }
    
    // MARK: - 私有方法
    private func showResult(_ message: String, type: ResultType,on view: UIView) {
        DispatchQueue.main.async {
            
            self.currentHUD?.hide(animated: false)
            
            let hud = MBProgressHUD.showAdded(to: view, animated: true)
            hud.mode = .customView
            hud.isUserInteractionEnabled = false
            hud.detailsLabel.text = message
            hud.detailsLabel.font = UIFont.systemFont(ofSize: 16)
            
            // 设置图标
            let image: UIImage?
            switch type {
            case .success:
                image = UIImage(systemName: "checkmark.circle.fill")?.withRenderingMode(.alwaysTemplate)
                hud.customView = UIImageView(image: image)
            case .error:
                image = UIImage(systemName: "xmark.circle.fill")?.withRenderingMode(.alwaysTemplate)
                hud.customView = UIImageView(image: image)
            }
            hud.bezelView.style = .solidColor // 使用纯色背景
            hud.bezelView.backgroundColor = .colorWithHex("#000000", alpha: 0.4)
            hud.contentColor = .white
            hud.removeFromSuperViewOnHide = true
            hud.hide(animated: true, afterDelay: 3)
            self.currentHUD = hud
        }
    }
    
 
    
    private enum ResultType {
        case success
        case error
    }
}
